/*
 *  xfelp-xfcedoc.c - This file is part of Xfelp
 *
 *  Copyright (C) 2008 Daniel Morales <daniel@daniel.com.uy>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string.h>

#include <glib.h>

#include "xfelp-xfcedoc.h"

gchar *
xfelp_xfcedoc_localize_file (const gchar *file,
                             const gchar *default_locale)
{
  const gchar *locale;
  char         buffer[PATH_MAX];
  char         delim[] = { '.', '@', '_' };
  int          count;

#ifdef HAVE_SETLOCALE
  if ((locale = setlocale (LC_MESSAGES, NULL)) == NULL)
#endif
    if ((locale = g_getenv ("LANGUAGE")) == NULL)
      if ((locale = g_getenv ("LANG")) == NULL)
        locale = "C";

  g_snprintf (buffer, PATH_MAX, file, locale);

  if (g_file_test (buffer, G_FILE_TEST_IS_REGULAR)) {
    return g_strdup (buffer);
  }

  for (count = 0; count < G_N_ELEMENTS (delim); count++)
  {
    char *langext, *p;
    char c = delim[count];

    if ((p = strchr (locale, c)) != NULL)
    {
      int s = p - locale;

      langext = g_new (char, s + 1);
      g_strlcpy (langext, locale, s + 1);

      g_snprintf (buffer, PATH_MAX, file, langext);

      g_free (langext);

      if (g_file_test (buffer, G_FILE_TEST_IS_REGULAR)) {
	      return g_strdup (buffer);
	  }
	}
  }

  /* Use the default locale */
  g_snprintf (buffer, PATH_MAX, file, default_locale);
  
 return g_strdup (buffer);
}

gchar *
xfelp_xfcedoc_get_home (void)
{
  return xfelp_xfcedoc_localize_file (XFELP_XFCEDOC_DEFAULT_HOME, XFELP_XFCEDOC_DEFAULT_LOCALE);
}
